import telnetlib
import threading
import subprocess
import time

class Openocd:
    def __init__(self):
        self.tn = None
        self.lock = threading.Lock()
        self.stop_event = None
        self.XPXH = None
        self.BBH = None
        self.password = None

    def thread_function(self):
        self.stop_event = threading.Event()

        command = ['./openocd/bin/openocd.exe', '-f', f'./openocd/profile/{self.XPXH}/{self.BBH}/config/haawking.cfg',
               '-u', f'{self.password}']
        print(command)
        openocd_process = subprocess.Popen(command)
        # 判断对象的状态是否为真
        while not self.stop_event.is_set():
            time.sleep(1)
        openocd_process.kill()


    def setEvent(self):
        self.stop_event.set()
    def connect(self, XPXH, BBH ,password,timeout=5):
        self.XPXH = XPXH
        self.BBH = BBH
        self.password = password
        print("启动Openocd")
        thread = threading.Thread(target=self.thread_function)
        thread.start()
        time.sleep(6)

        try:
            self.tn = telnetlib.Telnet('127.0.0.1', 4444, timeout)
            return True
        except Exception as e:
            print('[ERROR] Connection failed:', e)
            print("连接失败")
            self.setEvent()
            thread.join(1)
            # self.gpt.QHLX(self.comName)
            # time.sleep(1)
            # self.gpt.QHZX(self.comName)
            return self.connect(XPXH, BBH , password)

    def send(self, command):
        self.tn.write(command.encode('utf-8') + b"\n")

    def read(self):
        output = self.tn.read_very_eager()
        return output

    def close(self):
        self.tn.close()


# if __name__ == "__main__":
#     aa = Openocd()
#     aa.connect("HXS320F28027","ECD")